package com.xhc.demo.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WxPayCertificateUtil {
    private static final Logger logger = LoggerFactory.getLogger(WxPayCertificateUtil.class);

    public static String getCertificateSerialNumber(String certPath, String mchId) {
        try {
            // 加载证书
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(certPath);
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            in.close();

            // 获取证书序列号
            String serialNo = cert.getSerialNumber().toString(16).toUpperCase();
            logger.info("[PAY] Read certificate serial number: {} from path: {}", serialNo, certPath);
            return serialNo;
        } catch (CertificateException | IOException e) {
            logger.error("[PAY] Failed to get certificate serial number", e);
            throw new RuntimeException("Failed to get certificate serial number", e);
        }
    }
}
